package cn.chiship.sdk.core.util;

import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.exception.custom.BusinessException;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

/**
 * CSV工具类
 *
 * @author lijian
 */
public class CsvUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(CsvUtils.class);

	private static InputStream is;

	public static void load(String file) throws IOException {
		is = new FileInputStream(file);
	}

	public static void load(InputStream in) {
		is = in;
	}

	private static boolean checkAndCreateFile(String fileName) {

		File file = new File(fileName);
		try {
			if (!file.exists()) {
				file.createNewFile();
				return false;
			}
			else {
				return true;
			}
		}
		catch (Exception e) {
			LOGGER.error("发生异常", e);
			return false;
		}
	}

	public static BaseResult readCsv() throws IOException {
		ArrayList<String[]> list = new ArrayList<>();
		try {
			CsvReader reader = new CsvReader(is, ',', Charset.forName("gb2312"));
			while (reader.readRecord()) {
				list.add(reader.getValues());
			}
			reader.close();
			if (list.isEmpty()) {
				return BaseResult.error("CSV文件无数据!");
			}
			List<String> titles = new ArrayList<>();
			for (int i = 0; i < list.get(0).length; i++) {
				titles.add(list.get(0)[i]);
			}
			List<Map<String, String>> dataList = new ArrayList();
			if (list.size() > 1) {
				for (int row = 1; row < list.size(); row++) {
					int length = list.get(row).length;
					if (length > 0) {
						Map<String, String> dataMap = new HashMap<>(2);
						for (int i = 0; i < list.get(row).length; i++) {
							dataMap.put(titles.get(i), list.get(row)[i]);
						}
						dataList.add(dataMap);
					}
				}
			}

			return BaseResult.ok(dataList);
		}
		catch (Exception e) {
			LOGGER.error("读取发生异常", e);
			return BaseResult.error("读取发生异常[" + e.getLocalizedMessage() + "]");
		}

	}

	public static byte[] getWriteCsvBytes(List<String> headers, List<List<String>> data) {

		try {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			CsvWriter wr = new CsvWriter(os, ',', Charset.forName("gb2312"));
			String[] header = new String[headers.size()];
			for (Integer i = 0; i < headers.size(); i++) {
				header[i] = headers.get(i);
			}
			wr.writeRecord(header);

			for (List<String> item : data) {
				String[] values = new String[headers.size()];
				for (Integer i = 0; i < item.size(); i++) {
					values[i] = item.get(i);
				}
				wr.writeRecord(values);
			}
			wr.close();
			return os.toByteArray();
		}
		catch (IOException e) {
			throw new BusinessException("CSV输出字节数组出错。" + e.getLocalizedMessage());
		}

	}

	public static BaseResult writeCsv(String file, List<String> headers, List<List<String>> data) throws IOException {
		checkAndCreateFile(file);
		return writeCsv(new FileOutputStream(file), headers, data);
	}

	public static BaseResult writeCsv(OutputStream os, List<String> headers, List<List<String>> data) {
		try {
			CsvWriter wr = new CsvWriter(os, ',', Charset.forName("gb2312"));
			String[] header = new String[headers.size()];
			for (Integer i = 0; i < headers.size(); i++) {
				header[i] = headers.get(i);
			}
			wr.writeRecord(header);

			for (List<String> item : data) {
				String[] values = new String[headers.size()];
				for (Integer i = 0; i < item.size(); i++) {
					values[i] = item.get(i);
				}
				wr.writeRecord(values);
			}
			wr.close();
			return BaseResult.ok();
		}
		catch (Exception e) {
			LOGGER.error("写入发生异常", e);
			return BaseResult.error("写入发生异常[" + e.getLocalizedMessage() + "]");
		}
	}

	public static void main(String[] args) throws Exception {
		/*
		 * CsvUtils.load("d:/demo.csv"); PrintUtil.console(readCSV());
		 *
		 * FileInputStream fileInputStream = new FileInputStream("d:/demo.csv");
		 * CsvUtils.load(fileInputStream); PrintUtil.console(readCSV());
		 */

		List<String> headerTitles = new ArrayList<>();
		headerTitles.add("序号");
		headerTitles.add("专职律师身份");
		headerTitles.add("性别");
		headerTitles.add("执业类别");
		ArrayList<List<String>> values = new ArrayList<>();
		int len = 21;
		for (Integer i = 0; i < len; i++) {
			List<String> s = new ArrayList<>();
			s.add(String.valueOf(i));
			s.add(i + "371428199111183212");
			s.add(i + "633180341827878912");
			s.add(i + "3");
			values.add(s);
		}
		// FileOutputStream os = new FileOutputStream("d:/1.csv");
		/// PrintUtil.console(writeCSV(os, headerTitles, values));
		PrintUtil.console(getWriteCsvBytes(headerTitles, values).length);

	}

}